<template>
  <div class="app-container">
    <div class="search-container" style="height: 320px;">
      <el-row :gutter="10">
        <el-col v-if="trDisabled" :span="1.5">
          <el-button plain type="primary" @click="handleAdd">
            <template #icon>
              <i-ep-plus/>
            </template>
            新增
          </el-button>
        </el-col>
        <el-col v-if="trDisabled" :span="1.5">
          <el-button :disabled="multiple" plain type="danger" @click="handleDelete">
            <template #icon>
              <i-ep-delete/>
            </template>
            删除
          </el-button>
        </el-col>
        <!-- <el-col v-if="trDisabled" :span="1.5">
          <el-button
            plain
            type="info"
            @click="handleImport"
          >
            <template #icon>
              <i-ep-upload/>
            </template>
            导入数据、导出模板
          </el-button>
        </el-col> -->
        <el-form-item v-if="!userInfo.orgId" label="机构">
          <select-org-tree :value="queryParams.orgId" class="width-120" @orgNodeClick="orgNodeClick"/>
        </el-form-item>
        <el-form-item label="权限" prop="authorityType">
          <el-select v-model="queryParams.authorityType" class="width-120" placeholder="请选择" @change="handleQuery">
            <el-option v-if="userInfo.customerType != '3'" label="所有" value="99">所有</el-option>
            <el-option v-for="dict in dictDataMap[
                    'template_authority_type'
                ]" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"/>
          </el-select>
        </el-form-item>
        <el-form-item label="模板名称" prop="title">
          <el-input v-model="queryParams.title" clearable placeholder="请输入模板主题名称"
                    @keyup.enter="handleQuery"/>
        </el-form-item>
        <el-form-item>
          <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery"/>
        </el-form-item>
      </el-row>
      <el-table :border="true" :data="templateMasterList" :header-cell-style="$headerCellStyle"
                :stripe="true" height="210px"
                highlight-current-row @row-click="rowClick" @selection-change="handleSelectionChange">
        <el-table-column :align="'center'" type="selection" width="55"/>
        <el-table-column :align="'center'" label="权限" prop="authorityType">
          <template #default="scope">
            <dict-data-tag :options="dictDataMap['template_authority_type']" :value="scope.row.authorityType"/>
          </template>
        </el-table-column>
        <el-table-column :align="'center'" label="模板归属人" prop="userName"/>
        <el-table-column :align="'center'" label="模板类型" prop="type">
          <template #default="scope">
            <dict-data-tag :options="dictDataMap['template_type']" :value="scope.row.type"/>
          </template>
        </el-table-column>
        <el-table-column :align="'center'" label="模板主题名称" prop="title"/>
        <el-table-column :align="'center'" label="适用科室" prop="deptName"/>
        <el-table-column :align="'center'" label="是否启用" prop="startFlag">
          <template #default="scope">
            <dict-data-tag :options="dictDataMap['sys_yes_no']" :value="scope.row.startFlag"/>
          </template>
        </el-table-column>
        <el-table-column v-if="trDisabled" :align="'center'" class-name="small-padding fixed-width" label="操作"
                         width="220">
          <template #default="scope">
            <el-button type="success" @click="handleUpdate(scope.row)">
              <template #icon>
                <i-ep-edit/>
              </template>
              修改
            </el-button>
            <el-button type="danger" @click="handleDelete(scope.row)">
              <template #icon>
                <i-ep-delete/>
              </template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum" :total="total"
                  @pagination="getList"/>
    </div>
    <div class="div-style mt10" style="height: calc(100% - 310px)">
      <template-ambulance-station-item v-if="detailIsShow" :to-station="toStation" @template-quote="templateQuote"
                                    ref="templateAmbulanceStationItemRef"  />
    </div>
    <!-- 添加或修改模板主记录对话框 -->
    <el-dialog v-model="open" :close-on-click-modal="false" :title="title" append-to-body draggable
               width="500px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="权限" prop="authorityType">
          <el-select v-model="form.authorityType">
            <el-option v-for="dict in dictDataMap[
                                'template_authority_type'
                            ]" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模板名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入模板名称" @input="titleInput"/>
        </el-form-item>
        <el-form-item label="适用科室" prop="deptId">
          <base-dept-tree :org-id="form.orgId" :value="form.deptId" style="width: 100%;"
                          @deptSelect="deptSelect"/>
        </el-form-item>
        <el-form-item label="启用状态">
          <el-radio-group v-model="form.startFlag">
            <el-radio v-for="dict in dictDataMap['sys_yes_no']" :key="dict.dictValue"
                      :value="dict.dictValue">{{ dict.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
                    <span class="dialog-footer">
                        <el-button type="primary" @click="submitForm">确 定</el-button>
                        <el-button @click="cancel">取 消</el-button>
                    </span>
      </template>
    </el-dialog>

    <!-- 门诊病历模板导入 -->
    <el-dialog v-model="uploadOpen" :title="upload.title" append-to-body width="400px" @close="dialogClose">
      <el-upload ref="uploadRef" :auto-upload="false" :http-request="httpRequest" :limit="1"
                 :on-change="handleChange" :on-progress="handleFileUploadProgress" accept=".xlsx" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip text-center">
          <span>仅允许导入xlsx格式文件。</span>
          <el-link :underline="false" style="font-size:12px;vertical-align: baseline;" type="primary"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="dialogClose">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {
  addTemplateMaster,
  batchImportImportRecordTemplate,
  delTemplateMaster,
  getTemplateMaster,
  selectPageTemplateMaster,
  updateTemplateMaster
} from "@/api/patient/templateMaster.ts";
import {getDrugVsDeptList} from "@/api/drug/drugStorageDept.ts"
import {useUserStoreHook} from "@/store/modules/user";
import {useDictStoreHook} from "@/store/modules/dict";
import {firstLetterResult} from "@/utils/pinyin";
import templateAmbulanceStationItem from "./templateAmbulanceStationItem.vue";

const {proxy} = getCurrentInstance() as any;
const props = defineProps({
  trDisabled: {
    type: Boolean,
    default: true
  },
  queryParams: {
    type: Object as any
  },
  toStation: {
    type: Boolean,
    default: false
  }
})
const dictStore = useDictStoreHook();
const detailIsShow = ref(false)
let dictDataMap = ref(
  dictStore.isTypeGetData(
    "template_type",
    "sys_yes_no",
    "template_authority_type",
    "bill_item_class_dict"
  )
);

const useUserStore = useUserStoreHook();
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
const formRef = ref();
const templateAmbulanceStationItemRef = ref()
const templateMasterList = ref([]);
const multiple = ref(true);
const open = ref(false);
const total = ref(0);
const title = ref("");
const ids = ref([]);
const applyItem = ref<TemplateMasterType>({})
const emits = defineEmits(["templateQuote"])
// 药房list
const drugVsDeptList = ref<any>([])

const fileData = ref<any>(null)  // 文件上传数据（多文件合一）
const fileList = ref([])  // upload多文件数组
const uploadRef = ref()
//药品字典导入参数
const upload = ref<any>({
  // 弹出层标题
  title: "",
  // 是否禁用上传
  isUploading: false,

})
const uploadOpen = ref(false)
const queryParams = ref<TemplateMasterType>({
  pageNum: 1,
  pageSize: 10,
  type: "10",
  authorityType: userInfo.customerType != '3' ? '99' : "0",
  title: "",
  titleInput: "",
  deptId: userInfo.loginDeptId,
  orgId: userInfo.orgId,
});
const form = ref<TemplateMasterType>({
  type: "10",
  authorityType: "0",
  title: "",
  titleInput: "",
  deptId: "",
  deptName: "",
  storageId: "",
  startFlag: "Y",
  orgId: queryParams.value.orgId
});
const rules = {
  authorityType: [
    {
      required: true,
      message: "权限不能为空",
      trigger: "change",
    },
  ],
  title: [
    {
      required: true,
      message: "模板主题名称不能为空",
      trigger: "blur",
    },
  ],
  startFlag: [
    {
      required: true,
      message: "状态不能为空",
      trigger: "blur",
    },
  ],
  deptId: [
    {
      required: true,
      message: "科室不能为空",
      trigger: "blur",
    },
  ],
};

if (userInfo.orgId) {
  queryParams.value.orgId = userInfo.orgId
  // queryParams.value.authorityType = userInfo.customerType != '3' ? '' : "0"
  getList()
} else {
  queryParams.value.orgId = ""
}

// 以科室id查询对应的药房、药库信息
function getDrugVsDeptListFun() {
  let data = {
    deptId: form.value.deptId,
    orgId: userInfo.orgId,
    clinicOrVisitArray: proxy.$stringToArray("4,2,0", ","),
    storageTypeArray: proxy.$stringToArray("2,4", ","),
    drugGrantTypeArray: proxy.$stringToArray("1", ","),
  }
  getDrugVsDeptList(data).then((res: any) => {
    drugVsDeptList.value = res.data
  })
}

/** 查询模板主记录列表 */
function getList() {
  if (queryParams.value.orgId) {
    const params = {
      authorityType: queryParams.value.authorityType == '99' ? '' : queryParams.value.authorityType,
      pageNum: queryParams.value.pageNum,
      pageSize: queryParams.value.pageSize,
      type: queryParams.value.type,
      title: queryParams.value.title,
      orgId: queryParams.value.orgId,
    }

    selectPageTemplateMaster(params).then((response: any) => {
      templateMasterList.value = response.rows;
      total.value = response.total;
    });
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  if (!queryParams.value.orgId) {
    return ElMessage.error("请先选择机构");
  }
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.value.title = ""
  queryParams.value.authorityType = "99"
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  if (!queryParams.value.orgId) {
    return ElMessage.error("请先选择机构");
  }
  open.value = true;
  reset()
  nextTick(() => {
    templateAmbulanceStationItemRef.value.emptyItem()
  })
  detailIsShow.value = false
  title.value = "添加模板主记录";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  open.value = true;
  reset();
  const _templateMasterId = row.templateMasterId || ids.value;
  getTemplateMaster(_templateMasterId).then((response: any) => {
    form.value = response.data;
    title.value = "修改模板主记录";
  });
}

/** 提交按钮 */
function submitForm() {
  (formRef.value as any).validate((valid) => {
    if (valid) {
      if (form.value.templateMasterId) {
        updateTemplateMaster(form.value)
          .then(() => {
            ElMessage.success("修改成功");
            open.value = false;
            detailIsShow.value = false
            getList();
            nextTick(() => {
              templateAmbulanceStationItemRef.value.emptyItem()
            })
          })
      } else {
        addTemplateMaster(form.value)
          .then(() => {
            ElMessage.success("新增成功");
            open.value = false;
            detailIsShow.value = false
            getList();
            nextTick(() => {
              templateAmbulanceStationItemRef.value.emptyItem()
            })
          })
      }
    }
  });
}

// 表单重置
function reset() {
  form.value = {
    templateMasterId: "",
    type: "10",
    authorityType: "0",
    title: "",
    titleInput: "",
    deptId: "",
    deptName: "",
    storageId: "",
    startFlag: "Y",
    orgId: queryParams.value.orgId,
  };
  nextTick(() => {
    formRef.value.resetFields();
  });
}

// 机构树点击事件
function orgNodeClick(data, _e) {
  queryParams.value.orgId = data.orgId;
  if (queryParams.value.orgId) {
    getList();
  }
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.templateMasterId);
  multiple.value = !selection.length;
}


// 科室点击事件
function deptSelect(node) {
  form.value.deptId = node.deptId
  form.value.deptName = node.deptName
  getDrugVsDeptListFun()
}

// 主题生成拼音码
function titleInput(value) {
  if (value) {
    form.value.titleInput = firstLetterResult(value)
  } else {
    form.value.titleInput = ""
  }
}

// 主表行点击事件
function rowClick(row: any) {
  applyItem.value = row
  detailIsShow.value = true
  nextTick(() => {
    templateAmbulanceStationItemRef.value.rowClickClick(row)
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _templateMasterIds = row.templateMasterId || ids.value;
  ElMessageBox.confirm("是否确认删除模板数据项？", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      delTemplateMaster(_templateMasterIds).then(() => {
        getList();
        ElMessage.success("删除成功");
      });
    })
    .catch(() => {
    });
}

/**
 * 子模板的引用方法
 * @param form
 */
function templateQuote(form) {
  emits("templateQuote", form)
}

onMounted(() => {
  getList();
})

/** 导入按钮操作 */
function handleImport() {
  upload.value.title = "门诊病历模板导入";
  uploadOpen.value = true;
}


//监控上传文件列表
function handleChange(file, fileListInfo) {
  let existFile = fileListInfo.slice(0, fileListInfo.length - 1).find((f) => f.name === file.name)
  if (file.name.substring(file.name.lastIndexOf(".") + 1, file.name.length) !== 'xlsx') {
    fileListInfo.pop()
    return ElMessage.error('上传的文件类型不是.xlsx文件，请重新上传!')
  }
  if (existFile) {
    ElMessage.error('当前文件已经存在!')
    fileListInfo.pop()
  }
  fileList.value = fileListInfo
}

// 文件上传中处理
function handleFileUploadProgress(event, file, fileList) {
  upload.value.isUploading = true;
}


function httpRequest(file) {
  fileData.value.append('file', file.file) // append增加数据
}

function dialogClose() {
  fileData.value = []
  fileList.value = []
  uploadRef.value.clearFiles()
  getList()
  uploadOpen.value = false;
}


/** 下载模板操作 */
function importTemplate() {
  // this.download('system/user/importTemplate', {}, `user_template_${new Date().getTime()}.xlsx`)
}


function submitFileForm() {
  const link = document.createElement('a')
  fileData.value = new FormData() // new formData对象
  uploadRef.value.submit() // 提交调用uploadFile函数
  batchImportImportRecordTemplate(fileData.value).then((res: resType) => {
    ElMessage.success("正在导入，请稍等...")
    setTimeout(() => {
      dialogClose()
    }, 5000)
    const blob = new Blob([res.data], {type: 'application/octet-stream'})
    link.download = "门诊病历模板导入-错误数据.xlsx"
    let objectUrl = URL.createObjectURL(blob)
    link.href = objectUrl
    document.body.appendChild(link)
    // 下载文件
    link.click()
    // 释放内存
    window.URL.revokeObjectURL(objectUrl)
    document.body.removeChild(link)
  })
}

</script>

<script lang="ts">
export default {
  name: "templateAmbulanceStation"
}
</script>

<style scoped></style>
